using System;
using System.Reflection;

namespace WindowsPhone.CompactContainer.ServiceLocation.CompactContainer
{
    /// <summary>
    /// 
    /// </summary>
    public class PropertyDataResolver : IPropertyDataResolver
    {
        private const char Separator = ',';

        private readonly IContainer _container;

        /// <summary>
        /// Initializes a new instance of the <see cref="PropertyDataResolver"/> class.
        /// </summary>
        /// <param name="container">The container.</param>
        public PropertyDataResolver(IContainer container)
        {
            _container = container;
        }

        /// <summary>
        /// Gets the specified qualifier.
        /// </summary>
        /// <param name="qualifier">The qualifier.</param>
        /// <returns></returns>
        public PropertyData Get(string qualifier)
        {
            PropertyData data = new PropertyData();

            string[] parts = qualifier.Split(Separator);
            string typeName = parts[0].Trim();
            string assemblyName = parts[1].Trim();
            data.Name = parts[2].Trim();

            Type type = Type.GetType(typeName + ", " + assemblyName, true);
            data.Owner = _container.Resolve(type);
            data.Info = type.GetProperty(data.Name, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
            data.Value = data.Info.GetValue(data.Owner, null);

            return data;
        }
    }
}